import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { Search, Tag, Image } from 'react-vant';
import { ListItemType } from '../home'
const Index = () => {
	const [value, setValue] = useState('');
	const [isShow, setIsShow] = useState(false);
	const [list, setList] = useState<ListItemType[]>([])
	const [searchList, setSearchList] = useState<string[]>(JSON.parse(localStorage.getItem('searchList') || '[]'));
	const [height, setHeight] = useState<number | string>(20)

	useEffect(() => {
		localStorage.setItem('searchList', JSON.stringify(searchList))
	}, [searchList])

	const fetchSearchList = async (value: string) => {
		const resp = await axios.get('/api/list', { params: { value } });
		console.table(resp.data.data);
		setList(resp.data.data)
	}
	const onSearch = (value: string) => {
		setValue(value)
		setSearchList([...new Set([value, ...searchList])]);
		setIsShow(true)
		fetchSearchList(value)
	}

	return (
		<div>
			<Search value={value} onClear={() => setIsShow(false)} onChange={setValue} placeholder="请输入搜索关键词" onSearch={onSearch} />
			{
				isShow
					? (
						<div>
							{
								list.map(v => {
									return (
										<dl key={v.id}>
											<dt>
												<Image src={v.image} alt="" lazyload width={120} height={80} />
											</dt>
											<dd>
												<h3>{v.tilte}</h3>
												<p>{v.desc}</p>
											</dd>
										</dl>
									)
								})
							}
						</div>
					)
					: (
						<div>
							<h3 style={{ display: 'flex', justifyContent: 'space-between' }}>
								<span>搜索历史记录 <Tag style={{ transform: height === 20 ? 'rotateZ(0)': 'rotateZ(180deg)' }} onClick={() => {
									if (height === 20) {
										setHeight('auto')
									} else {
										setHeight(20)
									}
								}}>^</Tag> </span>
								<span onClick={() => setSearchList([])}>删除</span>
							</h3>
							<div style={{ height, overflow: 'hidden' }}>
								{searchList.map((v, i) => {
									return <Tag onClick={() => onSearch(v)} style={{ margin: 4 }} type="primary" key={i}>{v}</Tag>
								})}
							</div>
						</div>
					)
			}
		</div>
	)
}

export default Index